package com.hong.controller;

import com.hong.service.IZkService;
import com.hong.service.impl.WaterServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: csh
 * @Date: 2020/12/14 11:24
 * @Description:
 */
@RestController
@Slf4j
public class ZkController {
    @Autowired
    private IZkService zkService;

    @GetMapping("/create")
    public String create(String path,String data){
        path="/"+path;
        //查看节点是否存在
        Stat stat = zkService.exists(path, new WaterServiceImpl());
        if(null==stat){
            boolean node = zkService.createNode(path, data);
            String str = node?"成功":"失败";
            log.info("添加结果{}",str);
            return  str;
        }
        return "已存在，请不要重复添加!";
    }

    @GetMapping("/updateNode")
    public String updateNode(String path,String data){
        path="/"+path;
        //查看节点是否存在
        Stat stat= zkService.exists(path,new WaterServiceImpl());
        if(null == stat)
        {
            return "该节点不存在,请添加后重试！！";
        }

        if(zkService.updateNode(path,data))
        {
            return "修改成功";
        }

        return "修改失败";
    }


    @GetMapping("/getdata")
    private String getData(String path)
    {
        path="/"+path;
        Stat stat= zkService.exists(path,new WaterServiceImpl());
        if(null == stat)
        {
            return "节点不存在！";
        }

        return zkService.getData(path,new WaterServiceImpl());
    }

}
